<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>规格属性</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> 不同规格商品的活动库存、活动商品、活动规则等不同的参数的设置 </span>
    </div>
    <el-form-item v-if="formData.specType" label="商品规格" class="mb-0!">
      <ProductAttributes
        :is-detail="isDetail"
        :prop-form-data="formData"
        :property-list="propertyList"
        @success="generateSkus"
      />
      <el-button
        class="mb-10px mr-15px"
        v-if="propertyList.length == 0"
        @click="handleAttributesAdd"
        >添新加规格</el-button
      >
    </el-form-item>

    <section v-for="(item, index) in formData!.skus" :key="index">
      <div
        v-if="propertyList.length && propertyList.length > 0 && item.properties"
        class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
      >
        <span>{{ item.properties[0].propertyName }}-{{ item.properties[0].valueName }} </span>
      </div>
      <el-form-item label="组合价" class="w-480px!">
        <div class="flex w-100%">
          <div class="flex-1">
            <el-form-item :prop="`skus[${index}][price]`" :rules="rules.price">
              <el-input
                v-model="item.price"
                class="w-100%!"
                :disabled="item.priceType == 1"
                @blur="handleChange(item)"
                :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
              >
                <template #prepend>
                  <el-select
                    v-model="item.priceType"
                    class="w-120px!"
                    @change="(e) => priceTypeChange(e, item)"
                  >
                    <el-option
                      v-for="(item, index) in priceTypeList"
                      :label="item.typeName"
                      :value="item.typeCode"
                      :key="index"
                    />
                  </el-select>
                </template>
                <template #suffix> 元 </template>
              </el-input>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="划线价" class="w-480px!">
        <div class="flex w-100%">
          <div class="flex-1">
            <el-form-item :prop="`skus[${index}][marketPrice]`">
              <el-input-number
                class="w-100%!"
                v-model="item.marketPrice"
                :precision="2"
                :controls="false"
              >
                <template #suffix> 元 </template>
              </el-input-number>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="最低价" class="w-480px!">
        <div class="flex w-100%">
          <div class="flex-1">
            <el-form-item :prop="`skus[${index}][lowPrice]`">
              <el-input-number
                class="w-100%!"
                v-model="item.lowPrice"
                :precision="2"
                :controls="false"
              >
                <template #suffix> 元 </template>
              </el-input-number>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品库存" :prop="`skus[${index}][stock]`" :rules="rules.stock">
        <el-input-number v-model="item.stock" :controls="false" class="w-360px!" />
      </el-form-item>
      <el-form-item label="组合商品">
        <el-button @click="handleGiveGoods(item)">选择商品</el-button>
        <SkuList
          class="mt-20px"
          ref="skuListRef"
          :isComponent="false"
          :isDetail="false"
          :hide-stock="true"
          :prop-form-data="item.spuData"
          :rule-config="ruleConfig"
          @delete="handleChange(item)"
        >
          <template #extension>
            <el-table-column align="center" label="必选" min-width="90">
              <template #default="{ row }">
                <el-switch v-model="row.productConfig.selected" />
              </template>
            </el-table-column>

            <el-table-column align="center" label="组合价" min-width="168">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.productConfig.discountPrice"
                  :disabled="item.priceType == 0"
                  @change="handleChange(item)"
                  :precision="2"
                >
                  <template #suffix> 元 </template>
                </el-input-number>
              </template>
            </el-table-column>

            <el-table-column align="center" label="数量" min-width="168">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.productConfig.activityProductCount"
                  @change="handleChange(item)"
                  :min="1"
                  :precision="0"
                />
              </template>
            </el-table-column>
          </template>
        </SkuList>
      </el-form-item>
      <!-- <el-form-item label="组合规则" class="w-480px!">
        <div class="flex w-100%">
          <div class="mr-10px"> 任选 </div>
          <div class="flex-1">
            <el-form-item :prop="`skus[${index}][number]`" :rules="rules.number">
              <el-input-number
                class="w-100%!"
                v-model="item.number"
                :precision="0"
                :controls="false"
              >
                <template #suffix> 类 </template>
              </el-input-number>
            </el-form-item>
          </div>
        </div>
      </el-form-item> -->
      <el-form-item label="抵扣设置">
        <div class="w-100%">
          <el-checkbox-group v-model="item.deductionScopes">
            <el-checkbox
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_NTON_DEDUCTION_TYPES)"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item label="修改设置" class="w-480px!" v-if="formData.salesChannel?.includes(1)">
        <div class="w-100%">
          <el-checkbox v-model="item.isUpdated">允许门店修改 </el-checkbox>
        </div>
      </el-form-item>
    </section>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>分销设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="分销开关" props="subCommissionEnable">
      <el-switch
        v-model="formData.subCommissionEnable"
        @change="changeSubCommissionEnable"
      ></el-switch>
    </el-form-item>
    <el-form-item label="分销类型" props="subCommissionType" v-if="formData.subCommissionEnable">
      <el-radio-group
        v-model="formData.subCommissionType"
        class="w-80"
        @change="changeSubCommissionType"
      >
        <el-radio :value="false">默认设置</el-radio>
        <el-radio :value="true" class="radio">单独设置</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData!.subCommissionType">
      <section>
        <el-table :data="formData!.skus">
          <template v-if="formData!.specType">
            <!--  根据商品属性动态添加 -->
            <el-table-column
              v-for="(item, index) in tableHeaders"
              :key="index"
              :label="item.label"
              align="center"
              min-width="120"
            >
              <template #default="{ row }">
                <span v-if="row.properties?.length > 0">
                  {{ row.properties[index]?.valueName }}
                </span>
              </template>
            </el-table-column>
          </template>
          <el-table-column align="center" label="一级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.firstBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="一级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.firstBrokerageType == 2"
                v-model="row.firstBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.firstBrokerageType == 1"
                v-model="row.firstBrokeragePercent"
                :max="100"
                :formatter="verifyNumberPercentage"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.secondBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.secondBrokerageType == 2"
                v-model="row.secondBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.secondBrokerageType == 1"
                v-model="row.secondBrokeragePercent"
                :formatter="verifyNumberPercentage"
                :max="100"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>销量设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品在线下渠道有销售，可以填写该商品在线下渠道的销售数据。线上展示销量数据为线下销量+线上销量之和。
      </span>
    </div>
    <el-form-item label="线下销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData.virtualSalesCount"
        @change="virtualSalesCountChange"
        :min="0"
        placeholder="请输入线下销量"
        class="w-80!"
      />
    </el-form-item>
  </el-form>
  <GiveGoodsSelect ref="giveGoodsSelectRef" :isSelectSku="true" @confirm="selectSku" />
  <!-- 商品属性添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import {
  copyValueToTarget,
  fenToYuan,
  floatToFixed2,
  generateNumericUUID,
  generateSortNumericUUID,
  yuanToFen
} from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig
} from '@/views/mall/product/spu/components/index'
import type { Property, Spu } from '@/api/mall/product/spu'
import SkuList from '@/views/mall/product/components/SkuList.vue'
import GiveGoodsSelect from '@/views/mall/product/components/GiveGoodsSelect.vue'
import * as ProductSpuApi from '@/api/shop/product/spu'
import ProductAttributes from '@/views/mall/product/spu/form/ProductAttributes.vue'
import ProductPropertyAddForm from '@/views/mall/product/spu/form/ProductPropertyAddForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { cloneDeep } from 'lodash-es'
import { isEmpty } from '@/utils/is'
import { verifyNumberIntegerAndFloat, verifyNumberPercentage } from '@/utils/formatter'
defineOptions({ name: 'ProductSpuActivitySkuForm' })

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const formData = reactive<Spu>({
  spuType: 3,
  specType: true, // 商品规格
  salesChannel: [],
  virtualSalesCount: 0,
  subCommissionType: false, // 分销类型
  subCommissionEnable: false, //分销开关
  skus: [
    // {
    //   price: undefined, // 商品价格
    //   lowPrice: 0, //最低价
    //   marketPrice: 0, // 划线价
    //   costPrice: 0, // 成本价
    //   activityStartTime: '', //活动商品开始时间
    //   activityEndTime: '', //活动商品结束时间
    //   isUpdated: undefined, //N选N活动是否允许修改
    //   number: undefined, //活动N类
    //   deductionScopes: [], //N选N活动 活动抵扣设置类型
    //   generalProductList: [], //N选N活动关联商品列表
    //   skuType: 34, //商品属性
    //   stock: undefined,
    //   firstBrokeragePercent: 0, // 一级分销的佣金 比例
    //   secondBrokeragePercent: 0, // 二级分销的佣金 比例
    //   firstBrokerageType: 2, // 一级分销的佣金类型
    //   secondBrokerageType: 2, // 二级分销的佣金类型
    //   firstBrokeragePrice: 0, // 一级分销的佣金
    //   secondBrokeragePrice: 0, // 二级分销的佣金
    //   skuId: generateNumericUUID(), //商品 SKU 编号
    //   spuData: {
    //     skus: []
    //   }
    // }
  ]
})
const priceTypeList = ref<any>([
  {
    typeName: '一口价',
    typeCode: 0
  },
  {
    typeName: '累加价',
    typeCode: 1
  }
])
/**
 *
 *  价格或数量变化
 * @param nowItem
 */
const handleChange = (nowItem) => {
  if (nowItem.priceType == 0) {
    calculateItemDiscountPrice(nowItem)
  } else {
    calculatePrice(nowItem)
  }
}
const priceTypeChange = (e, nowItem) => {
  if (e == 0) {
    calculateItemDiscountPrice(nowItem)
  } else {
    calculatePrice(nowItem)
  }
}
const tableHeaders = ref<{ prop: string; label: string }[]>([]) // 多属性表头

const nowItem = ref() //当前选中的数据
const handleGiveGoods = (item: any) => {
  nowItem.value = item
  const selectedSkuIds = item.spuData.skus.map((ele) => {
    return ele.skuId
  })
  giveGoodsSelectRef.value.open(selectedSkuIds)
}
const handleAttributesAdd = () => {
  let data = {
    id: generateSortNumericUUID(),
    name: '',
    values: []
  }
  propertyList.value.push(data)
}
/** 生成表数据 */
const generateTableData = (propertyList: any[]) => {
  // 构建数据结构
  const propertyValues = propertyList.map((item) =>
    item.values.map((v: any) => ({
      propertyId: item.id,
      propertyName: item.name,
      valueId: v.id,
      valueName: v.name
    }))
  )
  const buildSkuList = build(propertyValues)
  // 如果回显的 sku 属性和添加的属性不一致则重置 skus 列表
  if (!validateData(propertyList)) {
    // 如果不一致则重置表数据，默认添加新的属性重新生成 sku 列表
    formData!.skus = []
  }
  for (const item of buildSkuList) {
    const row = {
      properties: Array.isArray(item) ? item : [item], // 如果只有一个属性的话返回的是一个 property 对象
      price: undefined, // 商品价格
      priceType: 0,
      lowPrice: 0, //最低价
      marketPrice: 0, // 划线价
      costPrice: 0, // 成本价
      activityStartTime: '', //活动商品开始时间
      activityEndTime: '', //活动商品结束时间
      isUpdated: undefined, //N选N活动是否允许修改
      number: undefined, //活动N类
      deductionScopes: [], //N选N活动 活动抵扣设置类型
      generalProductList: [], //N选N活动关联商品列表
      skuType: 34, //商品属性
      stock: undefined,
      firstBrokeragePercent: 0, // 一级分销的佣金 比例
      secondBrokeragePercent: 0, // 二级分销的佣金 比例
      firstBrokerageType: 2, // 一级分销的佣金类型
      secondBrokerageType: 2, // 二级分销的佣金类型
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      skuId: generateNumericUUID(), //商品 SKU 编号
      spuData: {
        skus: []
      }
    }

    // 设置el-tab-pane 对应的属性 直接关联到sku上
    // row.tabsName = row.properties[0].valueName

    // 如果存在属性相同的 sku 则不做处理
    const index = formData!.skus!.findIndex(
      (sku) => JSON.stringify(sku.properties) === JSON.stringify(row.properties)
    )
    if (index !== -1) {
      continue
    }
    formData!.skus!.push(row)
  }
}

/**
 * 生成 skus 前置校验
 */
const validateData = (propertyList: any[]) => {
  const skuPropertyIds: number[] = []
  formData!.skus!.forEach((sku) =>
    sku.properties
      ?.map((property) => property.propertyId)
      ?.forEach((propertyId) => {
        if (skuPropertyIds.indexOf(propertyId!) === -1) {
          skuPropertyIds.push(propertyId!)
        }
      })
  )
  const propertyIds = propertyList.map((item) => item.id)
  return skuPropertyIds.length === propertyIds.length
}

/** 构建所有排列组合 */
const build = (propertyValuesList: Property[][]) => {
  if (propertyValuesList.length === 0) {
    return []
  } else if (propertyValuesList.length === 1) {
    return propertyValuesList[0]
  } else {
    const result: Property[][] = []
    const rest = build(propertyValuesList.slice(1))
    for (let i = 0; i < propertyValuesList[0].length; i++) {
      for (let j = 0; j < rest.length; j++) {
        // 第一次不是数组结构，后面的都是数组结构
        if (Array.isArray(rest[j])) {
          result.push([propertyValuesList[0][i], ...rest[j]])
        } else {
          result.push([propertyValuesList[0][i], rest[j]])
        }
      }
    }
    return result
  }
}
const generateSkus = (propertyList: any[]) => {
  generateTableData(propertyList)
  Object.assign(props.propFormData, formData)
  // handleTabsEdit(propertyList[0].values[propertyList[0].values.length - 1].name, 'add')
}
/**虚拟销量 */
const virtualSalesCountChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 分销类型 */
const changeSubCommissionEnable = () => {
  formData.subCommissionType = false
  Object.assign(props.propFormData, formData)
}
const changeSubCommissionType = () => {
  // 默认为零，类型切换后也要重置为零
  for (const item of formData.skus!) {
    item.firstBrokeragePrice = 0
    item.secondBrokeragePrice = 0
  }
  Object.assign(props.propFormData, formData)
}
const rules = reactive({
  stock: [required],
  price: [required],
  number: [required]
})

// ================= 商品选择相关 =================
export interface DiscountProductVO {
  spuId: number
  skuId: number
  discountPrice?: number
  discountType: number
  selected: boolean
  activityProductCount: number
}
const giveGoodsSelectRef = ref() // 商品和属性选择 Ref
const skuListRef = ref() // sku   配置组件Ref
const ruleConfig: RuleConfig[] = [
  // {
  //   name: 'productConfig.discountPrice',
  //   rule: (arg) => arg > 0,
  //   message: '商品优惠金额不能为 0 ！！！'
  // }
]
const selectSku = (skuIds: number[]) => {
  getSkuDetails(skuIds, undefined, nowItem.value)
}

/** 获取SKU详情 */
const spuData = ref({
  skus: []
}) //为了统一组件格式
const getSkuDetails = async (
  skuIds: number[] | undefined,
  products?: DiscountProductVO[],
  nowItem?: any
) => {
  const data = await ProductSpuApi.getSkuPageList2({ skuIds } as any)
  if (data.list.length == 0) {
    return
  }
  console.log(nowItem)
  data.list.forEach((sku) => {
    let config: DiscountProductVO = {
      skuId: sku.skuId!,
      spuId: sku.spuId!,
      discountPrice: undefined,
      discountType: 1,
      activityProductCount: 0,
      selected: false
    }

    const existData = nowItem.spuData.skus.find((ele: any) => {
      return ele.skuId == sku.skuId
    })
    if (existData) {
      config = existData.productConfig
    }

    if (typeof products !== 'undefined') {
      const product = products.find((item) => item.skuId === sku.skuId)
      if (product) {
        product.discountPrice = fenToYuan(product.discountPrice!) as any
      }
      config = product || config
    }
    sku.productConfig = config
    sku.price = floatToFixed2(sku.price)
  })
  if (nowItem) {
    nowItem.spuData = {
      skus: []
    }
    data.list.forEach((ele) => {
      ele.salesPrice = ele.price
    })

    nowItem.spuData.skus = data.list
    setTimeout(() => {
      calculateItemDiscountPrice(nowItem)
    }, 100)
  }
}
//计算活动累加价
const calculatePrice = (nowItem) => {
  let price = 0
  nowItem.spuData.skus.forEach((ele) => {
    price +=
      Number(yuanToFen(ele.productConfig.discountPrice)) *
      Number(ele.productConfig.activityProductCount)
  })
  nowItem.price = fenToYuan(price)
}
//计算 参与组合商品总零售价
const calculateTotalPrice = (nowItem) => {
  return new Promise<any>((resolve) => {
    let totalPrice = 0 //单个商品总活动一口价
    nowItem.spuData.skus.forEach((ele) => {
      totalPrice += Number(yuanToFen(ele.price)) * Number(ele.productConfig.activityProductCount)
    })
    resolve(totalPrice)
  })
}
//计算一口价下每个商品的活动价格
const calculateItemDiscountPrice = (nowItem) => {
  let price = nowItem.priceType == 0 ? Number(yuanToFen(nowItem.price)) : 0 //活动一口价
  // let totalPrice = 0 //总零售价
  // let totalDiscountPrice = 0 //单个商品总活动一口价
  // nowItem.spuData.skus.forEach((ele) => {
  //   totalPrice += Number(yuanToFen(ele.price) * Number(ele.productConfig.activityProductCount))
  // })
  calculateTotalPrice(nowItem).then((totalPrice) => {
    nowItem.spuData.skus.forEach((ele) => {
      let rate = Number(yuanToFen(ele.price)) / totalPrice

      ele.productConfig.discountPrice = Number(fenToYuan(price * rate))
      // totalDiscountPrice += Number(yuanToFen(ele.productConfig.discountPrice))
    })
  })
}

/**
 * 获取所有 sku 活动配置
 *
 * @param extendedAttribute 在 sku 上扩展的属性，例：秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
 */
const getSkuConfigs = (extendedAttribute: string, item: any) => {
  skuListRef.value[0].validateSku()
  const products: any[] = []
  item.spuData.skus?.forEach((sku: any) => {
    products.push(sku[extendedAttribute] as any)
  })
  return products
}
// ================= end =================
onMounted(() => {})
/** 将传进来的值赋值给 formData */

watch(
  () => props.propFormData,
  async (data) => {
    if (!data) {
      return
    }
    data.skus.forEach(async (element) => {
      if (!isEmpty(element.generalProductList)) {
        if (!element.hasRun) {
          element.hasRun = true

          await getSkuDetails(
            element.generalProductList?.map((sku) => sku.skuId),
            element.generalProductList,
            element
          )
        }
      }
    })
    // if (!isEmpty(data.skus![0].generalProductList)) {
    //   if (!hasRun.value) {
    //     hasRun.value = true

    //     await getSkuDetails(
    //       data.skus![0].generalProductList?.map((sku) => sku.skuId),
    //       data.skus![0].generalProductList
    //     )
    //   }
    // }

    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
    // 重置表头
    tableHeaders.value = []

    // 生成表头
    propertyList.value.forEach((item, index) => {
      // name加属性项index区分属性值
      tableHeaders.value.push({ prop: `name${index}`, label: item.name })
    })
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // // 校验 sku
    // GiveGoodsFormRef.value?.forEach((ele) => {
    //   ele.submitForm()
    // })
    // if (giveGoodsFormErrorInfo.value) {
    //   throw new Error(giveGoodsFormErrorInfo.value)
    // }
    await unref(formRef).validate()

    formData.skus!.forEach((element: any) => {
      const products = cloneDeep(getSkuConfigs('productConfig', element))
      products.forEach((item: DiscountProductVO) => {
        item.discountPrice = yuanToFen(item.discountPrice!)
      })
      element.generalProductList = products
      if (element.generalProductList.length == 0) {
        message.error('【活动商品】不完善，请填写相关信息')
        emit('update:activeName', 'sku')

        return
      }
    })

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【活动信息】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
